package com.itcm.skymail.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itcm.common.utils.R;
import com.itcm.skymail.cart.feign.ProductFeignService;
import com.itcm.skymail.cart.interceptor.CartInterceptor;
import com.itcm.skymail.cart.service.CartService;
import com.itcm.skymail.cart.to.UserInfoTo;
import com.itcm.skymail.cart.vo.CartItem;
import com.itcm.skymail.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 描述:
 *
 * @author cm_fighting
 * @create 2020-11-22 7:40 下午
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    private final String CART_PREFIX = "skymall:cart:";

    /*
     * 购物车数据先存放在 redis中
     * 存放在redis中的数据类型 选择 hash, 即 k1: <k2, v>
     * k1 则为用户唯一标识 登录userId/未登录user-key对应的值
     * K2 skuId
     */
    @Override
    public CartItem addCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        CartItem item = new CartItem();

        CompletableFuture<Void> skuInfoTask = CompletableFuture.runAsync(() -> {
            // 远程调用商品服务 查询商品详情信息
            R info = productFeignService.info(skuId);
            if (info.getCode() == 0) {
                Object skuInfo = info.get("skuInfo");
                SkuInfoVo skuInfoVo = new ObjectMapper().convertValue(skuInfo, SkuInfoVo.class);
                log.info("远程调用返回skuInfo: {}", skuInfoVo);
                item.setCheck(true);
                item.setCount(num);
                item.setImage(skuInfoVo.getSkuDefaultImg());
                item.setPrice(skuInfoVo.getPrice());
                item.setSkuId(skuId);
                item.setTitle(skuInfoVo.getSkuTitle());
            } else {
                log.info("远程调用商品服务获取skuInfo异常");
            }
        }, executor);

        CompletableFuture<Void> skuAttrTask = CompletableFuture.runAsync(() -> {
            // 远程调用商品服务 查询商品销售属性
            List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
            item.setSkuAttr(skuSaleAttrValues);
        }, executor);
        CompletableFuture.allOf(skuInfoTask, skuAttrTask).get();
        cartOps.put(skuId.toString(), JSON.toJSONString(item));
        return item;
    }

    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey;
        if (userInfoTo.getUserId() != null) {
            // 登录状态下操作购物车
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        // redisTemplate 操作hash,绑定一个k，返回一个opertions，然后利用此operations对k对应的数据做crud...
        return redisTemplate.boundHashOps(cartKey);
    }
}
